<template>
  <el-dialog class="pick-dialog" title="申请售后" :visible.sync="dialogVisible" :close-on-click-modal="false" width="1000px">
    <div class="form-box">
      <div class="order-info flex">
        <span>
          订单状态：
          <span class="status-txt">{{ commonMaps.orderStatusMap[info.orderStatus] }}</span>
        </span>
        <span>订单编号：{{ info.no }}</span>
        <span>创建时间：{{ info.createTime }}</span>
        <span v-if="info.orderStatus==3">超时时间：{{ info.closeTime }}</span>
        <span v-if="info.cancelTime">取消时间：{{ info.cancelTime }}</span>
      </div>
      <div class="card-box">
        <el-table :data="infoArr" border style="width: 100%">
          <el-table-column prop="goodsId" label="商品编号" width="100">
          </el-table-column>
          <el-table-column prop="gameName" label="游戏名称" width="100">
          </el-table-column>
          <el-table-column prop="qufu" width="100" label="区服">
          </el-table-column>
          <el-table-column prop="des" label="简介">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.des" placement="top-start">
                <div class="zdy-des">{{ scope.row.des }}</div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="platformAmount" width="100" label="售价" ></el-table-column>
        </el-table>
      </div>

      <el-form :model="ruleForm" ref="ruleForm" label-width="auto" :rules="rules" class="demo-ruleForm">
        <el-form-item label="实付金额:" prop="">
          
          <span style="font-size:18px">¥{{info.actualAmount}}</span>

          <span style="margin-left: 20px;">
            <b>已退款金额：</b>
            <span style="font-size: 20px;color: red;">¥ {{ sumAmount }}</span>
          </span>
        </el-form-item>
        <el-form-item label="售后类型:" prop="afterType" v-if="info.type==1&&info.orderStatus!=1">
          
          <el-radio-group v-model="ruleForm.afterType">
            <el-radio :label="key" v-for="(value,key) in commonMaps.afterTypeMap" :key="key">{{value}}</el-radio>
          </el-radio-group>
          <div style="color:red;line-height: 1.5em;">提示：如果订单在交易中状态，选择“退款不退号”，售后处理完成后订单会变为交易成功；选择“退号退款”，售后处理完成后订单会变为交易失败。
            <br/>如果订单在交易成功状态，售后处理完成后订单状态不变。</div>
        </el-form-item>
        <el-form-item label="退款原因:" prop="afterReasonsName">
          <el-select v-model="ruleForm.afterReasonsName" placeholder="选择售后原因" style="width:250px" filterable
             clearable>
            <el-option v-for="(value,key) in afterReasons" :key="key" :label="value.dictLabel"
              :value="value.dictLabel"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="退款金额:" prop="afterAmount">
          <el-input style="width: 250px;" v-model="ruleForm.afterAmount" type="text"
            placeholder="请输入退款金额" @change="afterAmountChange"></el-input>
            <div class="tip">
              最多可退{{info.actualAmount - sumAmount}}元
            </div>
        </el-form-item>
        <el-form-item label="补充描述:" prop="afterRemark">
          <el-input style="width: 600px;" v-model="ruleForm.afterRemark" type="textarea" rows="5"
            placeholder="请输入售后补充描述..."></el-input>
        </el-form-item>
        <el-form-item label="上传图片:" prop="afterImg">
          <el-upload
            :action="uploadImgUrl"
            list-type="picture-card"
            :file-list="imgShowList0"
            :multiple="true"
            :on-preview="handlePictureCardPreview"
            :on-success="handleUploadSuccess0"
            :on-remove="handleRemove0"
            :limit="9"
            :headers="headers"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
   
     
      </el-form>
     
      <div class="center">
        <el-button @click="close('ruleForm')">取消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')" :loading="loading">提交售后</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import orderAfterApi from '@/api/pickUp/afterSale.js'
import { getUserProfile } from "@/api/system/user"
import { getToken } from "@/utils/auth";
export default {
  name: "afterOrder",
  data() {
    var priceRule = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入退款金额'));
        }else if (!this.priceReg.test(value)) {
            callback(new Error('请输入正确的退款金额'));
          } else if (value>this.info.actualAmount - this.sumAmount){
            callback(new Error('退款金额不能超过'+(this.info.actualAmount - this.sumAmount)));
          }else {
          
          callback();
        }
      };
    return {
      dialogVisible: false,
      loading: false,
      info: "",
      infoArr: [],
      userInfo: {},//当前登录人信息
      afterReasons:[],
      ruleForm: {
        saleOrderId: "",
        saleOrderNo: "",
        goodsId: "",
        applicantId:'',
        applicantName:'',
        afterType:'',
        afterAmount:'',
        afterReasonsId:'',
        afterReasonsName:'',
        afterRemark:'',
        afterImg:'',
      },
      rules:
      {
        afterType: [
          { required: true, message: '请选择售后类型', trigger: 'blur' }
        ],
        afterReasonsId:[
        { required: true, message: '请选择售后原因', trigger: 'blur' }
        ],
        afterAmount:[
        { required: true, message: '请输入退款金额', trigger: 'blur' },
          {validator:priceRule, trigger: 'blur'}
        ]
      },
      // 上传相关
      uploadImgUrl: "",
      imgShowList0: [],
      newImages0: [],
      imgFileList0: [],
      headers:{},


      fromPage:'',//来源
      sumAmount:0,//已经售后的金额
    };
  },
  created() {
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
    this.headers = {
        Authorization: "Bearer " + getToken(),
    };
  },
  methods: {
    open(info, flag) {
      //console.log("%c Line:194 🍭 info", "color:#ed9ec7", info);
      this.fromPage = flag
      this.loading = false
      this.info = info;
      this.sumAmount = 0
      // maxAmount = info.actualAmount
      this.infoArr = [info]
      this.ruleForm = {
        saleOrderId:info.id,
        saleOrderNo: info.no,
        goodsId: info.goodsId,
        applicantId:'',
        applicantName:'',
        afterType:this.info.orderStatus==1?1:'',
        afterAmount:'',
        afterReasonsId:'',
        afterReasonsName:'',
        afterRemark:'',
        afterImg:'',
      };
      this.getReasons()
      this.getCurrentInfo()
      this.saleOrderAftesumAmount(this.info.id)
      this.dialogVisible = true;
  
    },
    // 获取该订单已经售后的金额
    saleOrderAftesumAmount(saleOrderId){
      orderAfterApi.saleOrderAftesumAmount({
        saleOrderId:saleOrderId
      }).then(res=>{
        if(res.data.sumAmount){
          this.sumAmount = res.data.sumAmount
        }
      })
    },
    // 获取售后原因列表
    getReasons(){
      this.getDicts('afterReasons').then(res=>{
      this.afterReasons = res.data
    })
    },
    // 售后原因改变
    reasonChange(e){
      // this.ruleForm.afterReasonsName = this.commonMaps.afterReasonsMap[e]
    },
    afterAmountChange(e){

    },
    // 获取当前登录人信息
    getCurrentInfo() {
      getUserProfile().then(res => {
        //console.log("%c Line:186 🥒 登录信息res", "color:#fca650", res);
        this.userInfo = res.data
        this.ruleForm.applicantId = res.data.userId
        this.ruleForm.applicantName = res.data.nickName
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.loading = true
          // 组装图片附件
          // 拼接新上传的图片
          let ziliao = []
          if (this["newImages0" ] && this["newImages0" ].length) {
                let newArr = [];
                this["newImages0" ].forEach((img) => {
                  newArr.push({
                    name: img.name,
                    url: img.response.data.filePath,
                  });
                });
                ziliao = this["imgFileList0"].concat(newArr);
              } else {
                ziliao = this["imgFileList0"];
              }
          // ziliao
          //console.log("%c Line:212 🍖 ziliao", "color:#f5ce50", ziliao);
          this.ruleForm.afterImg = JSON.stringify(ziliao);
          orderAfterApi.saleOrderAfterAdd(this.ruleForm).then(res => {
            this.loading = false
            if (res.code == 200) {
              // 下单成功
              // // 跳转订单详情页面
              this.$message.success('售后申请已提交')
              this.$parent.getList()
              this.close()
            }
          }).catch(err=>{
            this.loading = false
          })


        } else {
          //console.log("error submit!!");
          return false;
        }
      });
    },

     // 上传图片相关
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url],
      });
    },
    uploadNumber(file, fileList) {
      //限制图片数量
      this.$modal.msgError("最多只能上传9张图片");
    },
    // 图片上传成功
    handleUploadSuccess0(res, file, fileList) {
      if (res.code == 200) {
        // 取得新上传的文件
        this.newImages0 = fileList.filter((t) => {
          return t.url.indexOf("blob:") > -1;
        });
      }
    },
    // 图片删除
    handleRemove0(response) {
      const that = this;
      // 1.获取将要删除图片的临时路径
      const filePath = response.url;
      // 2.找到图片对应的索引值
      this.imgFileList0.forEach(function (element, key) {
        if (element.url === filePath) {
          that.imgFileList0.splice(key, 1); //回显的图片
        }
      });
      this.newImages0.forEach(function (element, key) {
        if (element.url === filePath) {
          that.newImages0.splice(key, 1); //新上传的图片
        }
      });
    },
    close(formName) {
      this.dialogVisible = false
    }
  }
};
</script>
<style scoped lang="scss">
.order-info {
  box-sizing: border-box;
  // height: 50px;
  background: #eee;
  padding: 15px;
  margin-bottom: 10px;
  flex-wrap: wrap;
  line-height: 26px;

  >span {
    margin-right: 20px;
  }
}





.zdy-des {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 4;
  margin: 6px 0;
}





.demo-ruleForm {
  padding-right: 20px;
}

.center {
  text-align: right;
}



.pick-dialog>>>.el-input--medium input {
  text-align: left;
}
</style>
